import 'package:flutter/material.dart';

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("GridView Demo"),
        actions: [IconButton(onPressed: () {}, icon: Icon(Icons.share))],
      ),
      body: GridViewDemo(),
    );
  }
}

class GridViewDemo extends StatelessWidget {
  List<Widget> _girdItems = [
    Container(color: Colors.amber),
    Container(color: Colors.greenAccent),
    Container(color: Colors.blueAccent),
    Container(color: Colors.yellowAccent),
    Container(color: Colors.redAccent),
    Container(color: Colors.pinkAccent),
    Container(color: Colors.purpleAccent),
    Container(color: Colors.black26),
  ];
  @override
  Widget build(BuildContext context) {
    return Container(
      child: _builderGridView(),
    );
  }

  //GridView.count 构造器: 快速的创建横轴固定数量子元素的GridView, 默认gridDelegate为 SliverGridDelegateWithFixedCrossAxisCount
  //crossAxisCount 横轴上的个数(列)
  Widget _countGridView() {
    return GridView.count(
      crossAxisCount: 3,
      children: _girdItems,
      mainAxisSpacing: 10,
      crossAxisSpacing: 10,
    );
  }

  //GridView.extent 构造器: 快速的创建横轴子元素为固定最大长度的的GridView,默认gridDelegate为 SliverGridDelegateWithMaxCrossAxisExtent
  Widget _extentGridView() {
    return GridView.extent(
      maxCrossAxisExtent: 200,
      children: _girdItems,
      mainAxisSpacing: 10,
      crossAxisSpacing: 10,
    );
  }


  //动态加载 构造器: GridView.builder
  // 当子widget比较多时，我们可以通过GridView.builder来动态创建子widget
  Widget _builderGridView(){
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 10,
        crossAxisSpacing: 10
      ), 
      itemCount: _girdItems.length,
      itemBuilder: (context, index){
      return _girdItems[index];
    });
  }
}
